package cn.et.one;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

//消费者从队列消费
@RestController
public class Mail_Cons {
	//装配发送邮件的类
	@Autowired
	JavaMailSender jms;
	//将对象序列化为字节数组
		public static byte[] ser(Object obj) throws IOException{
			//接收被写入的字节数组
			ByteArrayOutputStream bos= new ByteArrayOutputStream();
			//把对象序列化成字节数组
			ObjectOutputStream oos= new ObjectOutputStream(bos);
			//写入
			oos.writeObject(obj);
			return bos.toByteArray();
		}
		//反序列化
		public static Object dser(byte[] src) throws Exception{
			//从字节数组读取数据
			ByteArrayInputStream bis = new ByteArrayInputStream(src);
			//把字节数组反序列化成对象
			ObjectInputStream ois= new ObjectInputStream(bis);
			return ois.readObject();	
		}
		//消费者消费的队列名称
	private static String QUEUE_NAME="MAILQueue";
	@GetMapping("/sends")
	public void asyncRec() throws Exception {
		
		 ConnectionFactory factory = new ConnectionFactory();  
	        factory.setHost("192.168.126.128");  
	        Connection connection = factory.newConnection();  
	        Channel channel = connection.createChannel();  
	        //消费者也需要定义队列 有可能消费者先于生产者启动   
	        channel.queueDeclare(QUEUE_NAME, false, false, false, null);  
	        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");  
	        //定义回调抓取消息  
	        Consumer consumer = new DefaultConsumer(channel) {  
	            @Override  
	            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,  
	                    byte[] body) throws IOException {  
	            	try {
						Map map=(Map) dser(body);
						SimpleMailMessage smm= new SimpleMailMessage();
						//设置发送方
						smm.setFrom("zmw960221@126.com");
						//设置收件方
						smm.setTo(map.get("sendto").toString());
						//设置邮件标题
						smm.setSubject(map.get("subject").toString());
						//设置邮件内容
						smm.setText(map.get("content").toString());
						jms.send(smm);
					} catch (Exception e) {
						e.printStackTrace();
					}
	            }  
	        };  
	        channel.basicConsume(QUEUE_NAME, true, consumer);  
	}
}
